package com.zalbert.woolgather

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder

class MainActivity : AppCompatActivity() {
    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val mAdapter = MainAdapter(
            this@MainActivity,
            mutableListOf(
                CoroutinesActivity::class.java
            )
        )
        findViewById<RecyclerView>(R.id.rv_main).apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(this@MainActivity, RecyclerView.VERTICAL, false)
        }
        mAdapter.notifyDataSetChanged()
    }
}

class MainAdapter(val context: Context, val data: MutableList<Class<*>>?) :
    RecyclerView.Adapter<MainAdapter.MainVideHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainVideHolder {
        return MainVideHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_main, parent, false)
        )
    }

    override fun onBindViewHolder(holder: MainVideHolder, position: Int) {
        holder.find<Button>(R.id.btn_goto)?.setOnClickListener {
            startActivity(context, Intent().setClass(context, data!![position]), null)
        }
        holder.find<Button>(R.id.btn_goto)?.text = data?.get(position)?.simpleName ?: ""
    }

    override fun getItemCount(): Int {
        return data?.size ?: 0
    }

    class MainVideHolder(view: View) : ViewHolder(view) {
        fun <T : View> find(id: Int): T? {
            return itemView.findViewById(id)
        }
    }
}